package com.fjwt.gz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.db.dto.MchGroupDTO;
import com.fjwt.gz.db.entity.AgentInfoEntity;
import com.fjwt.gz.db.entity.MchGroupEntity;
import com.fjwt.gz.db.entity.MchGroupMchEntity;
import com.fjwt.gz.db.dto.PointDTO;
import com.fjwt.gz.db.vo.MchGroupVO;
import com.fjwt.gz.service.mapper.MchGroupMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 商圈表 服务实现类
 * </p>
 *
 * @author shiyonghao
 * @since 2025-04-09
 */
@Slf4j
@Service
public class MchGroupService extends ServiceImpl<MchGroupMapper, MchGroupEntity> {


    @Autowired
    private AgentInfoService agentInfoService;

    @Autowired
    private MchGroupMchService mchGroupMchService;


    /**
     * 获取商圈列表
     *
     * @param iPage
     * @param groupDTO
     * @return
     */
    public IPage<MchGroupVO> getMchGroupList(IPage iPage, MchGroupDTO groupDTO) {
        LambdaQueryWrapper<MchGroupEntity> wrapper = MchGroupEntity.gw();
        wrapper.eq(StringUtils.isNotEmpty(groupDTO.getAgentNo()), MchGroupEntity::getAgentNo, groupDTO.getAgentNo())
                .eq(Objects.nonNull(groupDTO.getGroupType()), MchGroupEntity::getGroupType, groupDTO.getGroupType())
                .eq(StringUtils.isNotEmpty(groupDTO.getGroupNo()), MchGroupEntity::getGroupNo, groupDTO.getGroupNo())
                .like(StringUtils.isNotEmpty(groupDTO.getGroupName()), MchGroupEntity::getGroupName, groupDTO.getGroupName())
                .eq(Objects.nonNull(groupDTO.getState()), MchGroupEntity::getState, groupDTO.getState())
                .orderByDesc(MchGroupEntity::getCreatedAt);
        return this.page(iPage, wrapper);
    }

    /**
     * 新增商圈信息
     *
     * @param dto
     * @return
     */
    public void saveMchGroup(MchGroupDTO dto) {
        AgentInfoEntity agentInfo = checkAgentNo(dto.getAgentNo());
        dto.setAgentNo1(agentInfo.getAgentNo1());
        dto.setAgentNo2(agentInfo.getAgentNo2());
        dto.setAgentNo3(agentInfo.getAgentNo3());
        dto.setAgentNo4(agentInfo.getAgentNo4());
        dto.setGroupNo("MG" + DateUtil.format(new Date(), DatePattern.PURE_DATETIME_PATTERN));
        MchGroupEntity mchGroupEntity = BeanUtil.copyProperties(dto, MchGroupEntity.class);
        int result = baseMapper.add(mchGroupEntity);
        if (result != 1){
            throw new BizException("新增失败！");
        }
    }

    /**
     * 修改商户
     */
    public void updateMchGroup(MchGroupDTO dto) {
        AgentInfoEntity agentInfo = checkAgentNo(dto.getAgentNo());
        dto.setAgentNo1(agentInfo.getAgentNo1());
        dto.setAgentNo2(agentInfo.getAgentNo2());
        dto.setAgentNo3(agentInfo.getAgentNo3());
        dto.setAgentNo4(agentInfo.getAgentNo4());
        MchGroupEntity mchGroupEntity = BeanUtil.copyProperties(dto, MchGroupEntity.class);
        int result = baseMapper.updateByGroupNo(mchGroupEntity);
        if (result != 1){
            throw new BizException("修改失败！");
        }
    }

    /**
     * 校验机构
     * @param agentNo
     * @return
     */
    private AgentInfoEntity checkAgentNo(String agentNo) {
        AgentInfoEntity agentInfo = agentInfoService.getAgentInfo(agentNo);
        if (ObjectUtils.isEmpty(agentInfo)) {
            throw new BizException("所选机构不存在，请检查！");
        }
        return agentInfo;
    }

    public void saveGroupMch(MchGroupDTO dto, String url) {
        if(StringUtils.isEmpty(url)){
           throw new BizException("请求参数缺失！");
        }
        File file= FileUtil.file(String.format("./temp/%s.xlsx", DateUtil.date().getTime()));
        HttpUtil.downloadFile(url, file);
        ExcelReader excelReader = ExcelUtil.getReader(file, "Sheet1");
        // 可以加上表头验证
        // 3.读取第二行到最后一行数据
        List<List<Object>> read = excelReader.read(1, excelReader.getRowCount());
        List<MchGroupMchEntity> list = new ArrayList<>();
        for (List<Object> objects : read) {
            // 获取指定的的数据
            if(StringUtils.isEmpty(objects.get(0).toString())){
                continue;
            }
            MchGroupMchEntity groupMch = new MchGroupMchEntity();
            groupMch.setGroupNo(dto.getGroupNo());
            groupMch.setMchNo(String.valueOf(objects.get(0)));
            groupMch.setCreatedAt(new Date());
            list.add(groupMch);
        }
        excelReader.close();
        FileUtil.del(file);
        if (list.isEmpty()) {
            throw new BizException("导入数据为空！");
        }
        mchGroupMchService.saveBatch(list);
    }

    public void importGroupMchList(String groupMchList, String groupNo) {
        if(StringUtils.isEmpty(groupMchList) || StringUtils.isEmpty(groupNo)){
           throw new BizException("请求参数缺失！");
        }
        JSONArray array = JSONArray.parseArray(groupMchList);
        List<MchGroupMchEntity> list = new ArrayList<>();
        for(Object str:array){
            MchGroupMchEntity groupMch = new MchGroupMchEntity();
            groupMch.setGroupNo(groupNo);
            groupMch.setMchNo(String.valueOf(str));
            groupMch.setCreatedAt(new Date());
            list.add(groupMch);
        }
        if(list.isEmpty()){
            throw new BizException("参数错误！");
        }
         mchGroupMchService.saveBatch(list);
    }


    /**
     * 查询附近商圈
     * @param iPage
     * @param location
     * @param radius
     * @param agentNo
     * @param agentNo2
     * @return
     */
    public IPage<MchGroupVO> findNearGroupList(IPage iPage, PointDTO location, Integer radius, String agentNo, String agentNo2) {
        if (ObjectUtils.isEmpty(location) || ObjectUtils.isEmpty(radius)){
            throw new BizException("请求参数缺失！");
        }
        return baseMapper.findNearGroupList(iPage, location, radius, agentNo, agentNo2);
    }

    /**
     * 根据商圈编号查询商圈信息
     * @param groupNo
     * @return
     */
    public MchGroupVO getByGroupNo(String groupNo) {
        if (ObjectUtils.isEmpty(groupNo)){
            throw new BizException("请求参数缺失！");
        }
        MchGroupEntity entity = getById(groupNo);
        MchGroupVO vo = BeanUtil.copyProperties(entity, MchGroupVO.class);
        return vo;
    }

    /**
     * 删除商圈信息
     * @param groupNo
     */
    public void removeGroup(String groupNo) {
        if (ObjectUtils.isEmpty(groupNo)){
            throw new BizException("请求参数缺失！");
        }
        removeById(groupNo);
    }
}
